package activity.addCamera;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.location.LocationManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hichip.campro.R;
import com.hichip.tools.HiSearchSDK;

import java.util.ArrayList;
import java.util.List;

import base.HiActivity;
import butterknife.BindView;
import common.HiDataValue;
import common.TitleView;
import main.MainActivity;
import utils.HiToast;
import utils.HiTools;

/**
 * 无线连接添加设备   AP OR 声波
 */
public class SeleApOrSoundwaveActivty extends HiActivity implements View.OnClickListener {
    @BindView(R.id.title) TitleView title;
    private String mCurrentPhoneWiFi;
    @BindView(R.id.tv_sound_waves) TextView tv_sound_waves;
    @BindView(R.id.tv_ap_match_net) TextView tv_ap_match_net;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_sele_ap_or_soundwave;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        initViewAndData();
        setListeners();

    }

    private void setListeners() {
        tv_sound_waves.setOnClickListener(this);
        tv_ap_match_net.setOnClickListener(this);
    }

    private void initViewAndData() {
        title.setTitle(getString(R.string.title_select_net_type));
        title.setButton(TitleView.NAVIGATION_BUTTON_LEFT);
        title.setRightTxtBack(R.mipmap.x_bule);
        title.setNavigationBarButtonListener(new TitleView.NavigationBarButtonListener() {
            @Override
            public void OnNavigationButtonClick(int which) {
                switch (which) {
                    case TitleView.NAVIGATION_BUTTON_LEFT:
                        SeleApOrSoundwaveActivty.this.finish();
                        break;
                    case TitleView.NAVIGATION_BUTTON_IV_RIGHT:
                        Intent intent = new Intent(SeleApOrSoundwaveActivty.this, MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent, true);
                        break;
                }
            }
        });

    }

    private String maybeUid = "";

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_sound_waves://声波配网添加
                Intent intent = new Intent(SeleApOrSoundwaveActivty.this, SoundWavesReadyActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_ap_match_net://AP配网添加
                if (HiTools.isWifiConnected(SeleApOrSoundwaveActivty.this)) {
                    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                    String SSID = wifiManager.getConnectionInfo().getSSID();
                    mCurrentPhoneWiFi = SSID.substring(1, SSID.length() - 1);
                    if (!TextUtils.isEmpty(mCurrentPhoneWiFi) && mCurrentPhoneWiFi.startsWith(HiDataValue.START_WITH_IPCAM)) {//是IPCAM-开头的
                        String[] strs = mCurrentPhoneWiFi.split("-");
                        if (strs.length >= 2) {
                            maybeUid = strs[1];
                        }
                        showLoadDialog(getString(R.string.searching_device), false, false);
                        startSearch();
                    } else {//是正常WiFi
                        LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
                        boolean ok = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
                        if (ok) {
                            if (ContextCompat.checkSelfPermission(this, Manifest.permission_group.LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                // 获取wifi连接需要定位权限,没有获取权限
                                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_WIFI_STATE,}, 110);
                                return;
                            }
                        } else {
                            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                            dialog.setTitle(getString(R.string.tip_reminder)).setMessage(getString(R.string.open_location));
                            dialog.setPositiveButton(getString(R.string.go_to_open), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent();
                                    intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                    startActivityForResult(intent, 1315);
                                }
                            });
                            dialog.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            });
                            dialog.show();
                        }
                    }
                } else {
                    HiToast.showToast(SeleApOrSoundwaveActivty.this, getString(R.string.toast_connect_wifi));
                }
                break;
        }
    }

    private CountDownTimer timer;
    private HiSearchSDK searchSDK;

    private void startSearch() {
        int timeLong = 15000;
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        searchSDK = new HiSearchSDK(new HiSearchSDK.ISearchResult() {
            @Override
            public void onReceiveSearchResult(HiSearchSDK.HiSearchResult result) {
                String temp = result.uid.substring(0, 4);
                if (!TextUtils.isEmpty(temp)) {
                    Message msg = mHandler.obtainMessage();
                    msg.obj = result;
                    msg.what = HiDataValue.HANDLE_MESSAGE_SCAN_RESULT;
                    mHandler.sendMessage(msg);
                }
            }
        });
        searchSDK.search2();
        timer = new CountDownTimer(timeLong, 1000) {
            @Override
            public void onFinish() {
                dissmissLoadDialog();
                HiToast.showToast(SeleApOrSoundwaveActivty.this, getString(R.string.not_search_device));
                View customView = View.inflate(SeleApOrSoundwaveActivty.this, R.layout.pup_ipcam_search_fail, null);
                PopupWindow popupWindow = new PopupWindow(customView);
                ColorDrawable cd = new ColorDrawable(-000);
                popupWindow.setBackgroundDrawable(cd);
                popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
                popupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
                popupWindow.setFocusable(true);
                popupWindow.showAtLocation(customView, Gravity.CENTER, 0, 0);
                TextView tv_know = customView.findViewById(R.id.tv_know);
                tv_know.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                    }
                });
            }

            @Override
            public void onTick(long arg0) {

            }
        }.start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1315:
                if (ContextCompat.checkSelfPermission(this, Manifest.permission_group.LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // 获取wifi连接需要定位权限,没有获取权限
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_WIFI_STATE,}, 110);
                    return;
                }
                break;
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HiDataValue.HANDLE_MESSAGE_SCAN_RESULT:
                    HiSearchSDK.HiSearchResult searchResult = (HiSearchSDK.HiSearchResult) msg.obj;
                    if (searchResult != null && !TextUtils.isEmpty(searchResult.uid)) {
                        String[] strs = searchResult.uid.split("-");
                        if (strs.length > 2) {
                            if (!TextUtils.isEmpty(maybeUid) && maybeUid.equals(strs[1])) {
                                // ap热点 并搜索到了ap机器
                                dismissjuHuaDialog();
                                searchSDK.stop();
                                if (timer != null) {
                                    timer.cancel();
                                }
                                Intent intent = new Intent(SeleApOrSoundwaveActivty.this, ConfirmApDeviceActivity.class);

                                WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                                String SSID = wifiManager.getConnectionInfo().getSSID();
                                String ssid = SSID.substring(1, SSID.length() - 1);

                                intent.putExtra(HiDataValue.EXTRAS_KEY_UID, searchResult.uid);
                                intent.putExtra("ssid", ssid);
                                intent.putExtra("mCurrentPhoneWiFi", mCurrentPhoneWiFi);
                                startActivity(intent);
                            }
                        }
                    }
                    break;

            }
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        dissmissLoadDialog();
        if (searchSDK != null) {
            searchSDK.stop();
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (myScanResult != null) {
            myScanResult.clear();
        }
    }

    private List<ScanResult> myScanResult = new ArrayList<ScanResult>();

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 110:
                Log.i("tedu","--onRequestPermissionsResult--");
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {// 允许
                    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                    if (!wifiManager.isWifiEnabled()) {
                        wifiManager.setWifiEnabled(true);
                    }
                    wifiManager.startScan();
                    List<ScanResult> scanResults = wifiManager.getScanResults();
                    for (ScanResult scanResult : scanResults) {
                        String ssid = scanResult.SSID;
                        if (!TextUtils.isEmpty(ssid) && ssid.length() > 5) {
                            String subSSid = ssid.substring(0, 5);
                            if (subSSid.equalsIgnoreCase("IPCAM")) {
                                myScanResult.add(scanResult);
                            }
                        }
                    }
                    if (myScanResult.size() == 1) {
                        Intent intent = new Intent(SeleApOrSoundwaveActivty.this, APConnectActivity.class);
                        intent.putExtra("ssid", myScanResult.get(0).SSID);
                        intent.putExtra("mCurrentPhoneWiFi", mCurrentPhoneWiFi);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(SeleApOrSoundwaveActivty.this, SeleDevHotSpotActivity.class);
                        intent.putExtra("mCurrentPhoneWiFi", mCurrentPhoneWiFi);
                        startActivity(intent);
                    }
                } else {// 不允许
                    Toast.makeText(this, getString(R.string.no_permission), Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }


}
